# -*- coding:utf-8 -*-
"""
@Time : 2020-12-15 11:54
@Author: langengel
@Des: 服务商管理员
"""

from saas.response.BaseResponse import success, fail, res_antd
from models.saas import Service, User, Wechat, Role
from fastapi import Request, Query
from saas.utils.utils import zfill
from validator.user import CreateUser, UpdateAdminUser



async def admin_list(req: Request,
                     u_phone: str = Query(None),
                     create_time: list[str] = Query(None),  # Query(None, regex="^1[34567890]\\d{9}$") 手机号正则表达式
                     pageSize: int = Query(10),
                     current: int = Query(1),
                     full_name: str = Query(None),
                     ):
    """
    管理员列表+搜索
    :param req: Request
    :param u_phone: 手机号
    :param create_time: 创建时间
    :param pageSize: 没页条数
    :param current: 当前页
    :param full_name: 姓名
    :return:
    """
    # 提取查询条件
    query = {}
    if create_time:
        query["create_time__range"] = create_time
    if u_phone:
        query["u_phone"] = u_phone
    if full_name:
        query["full_name"] = full_name


    # 查询构造
    user = User().filter(**query, service=req.state.sid).all()
    # 获取查询总数
    count = await user.count()
    # 分页查询
    users = await user.limit(pageSize).offset(pageSize * (current - 1)).values(
        "id", "u_status", "nickname", "create_time", "update_time", "u_phone", "full_name", "remarks", "headimgurl",
        "type", "username", "client_host"
    )

    # 处理查询数据
    for user in users:
        user.update({"key": user.get("id")})

    return res_antd(data=users, total=count)


async def update_admin_user(req: Request, post: UpdateAdminUser):
    """
    更新管理员信息
    :param req:
    :param post:
    :return:
    """
    service = await Service.get_or_none(id=req.state.sid)
    user = await User.get_or_none(id=post.user_id, service=service)
    # 非超级管理员更新角色
    status = post.u_status
    if not user.type and post.roles:
        roles = await Role().filter(id__in=post.roles, service=service, role_status=True).all()
        await user.roles.clear()
        await user.roles.add(*roles)

    if user.type:
        status = 1
    if status == 0:
        status = 2

    # 当前登陆用户不能切换自己的账户状态
    if req.state.uid == post.user_id:
        status = user.u_status

    # 非超级管理员不能修改超级官员的名字 备注
    if not req.state.is_admin and user.type:
        return fail(msg="你没有修改超级管理员的信息的权限！")

    await user.update_from_dict({
        "remarks": post.remarks,
        "full_name": post.full_name,
        "u_status": status
    }).save()

    return success(msg="更新成功")


async def admin_user_role(req: Request, user_id: int):
    """
    获取服务商指定管理员拥有的角色
    :param req:
    :param user_id:
    :return:
    """
    user = await User().get_or_none(id=user_id, service=req.state.sid)

    if user.type:
        roles = await Role().filter(service=req.state.sid, role_status=True).values()
        for role in roles:
            role["key"] = role["id"]
            role["checked"] = True
            role["value"] = role.pop('id')
            role["label"] = role.pop('role_name')
        return success(data=roles, msg="角色列表")

    # 非超级管理员
    roles = await user.roles.all().values()
    for role in roles:
        role["checked"] = True
        role["key"] = role["id"]
        role["value"] = role.pop('id')
        role["label"] = role.pop('role_name')
    return success(data=roles, msg="角色列表")


async def get_admin_role(req: Request):
    """
    获取管理员拥有对角色
    :param req:
    :return:
    """
    # 超级管理员获取所有
    if req.state.uid:
        roles = await Role().filter(service=req.state.sid, role_status=True).values('id', 'role_name')
        for role in roles:
            role["key"] = role["id"]
            role["value"] = role.pop('id')
            role["label"] = role.pop('role_name')
        return success(data=roles, msg="角色列表")

    # 非超级管理员只能获取自己拥有的角色
    user = await User().get_or_none(id=req.state.uid, service=req.state.sid)
    roles = await user.roles.filter(service=req.state.sid, role_status=True).values('id', 'role_name')
    for role in roles:
        role["key"] = role["id"]
        role["value"] = role.pop('id')
        role["label"] = role.pop('role_name')
    return success(data=roles, msg="角色列表")


async def create_admin(req: Request, post: CreateUser):
    # 获取当前服务商
    service = await Service.get_or_none(id=req.state.sid)
    # 查询姓名重复
    check = await User().get_or_none(full_name=post.full_name, service=service)
    if check:
        return fail(msg="此姓名已经存在，请更换其他姓名")
    # 创建超级管理员
    add_user = await User.create(
        full_name=post.full_name,
        service=service,
        type=False,
        remarks=post.remarks,
        u_status=post.u_status

    )
    # 追加业务ID
    await add_user.update_from_dict({"u_id": zfill('8', add_user.pk, 10)}).save()

    if post.roles:
        roles = await Role().filter(id__in=post.roles, service=service)
        if roles:
            # 角色分配
            await add_user.roles.add(*roles)
    # 创建用户微信
    await Wechat().create(service=service, user=add_user)

    return success(msg="创建成功")


async def current_user(req: Request):
    """
    当前用户信息
    :param req:
    :return:
    """

    wechat_user = await Wechat().get_or_none(user=req.state.uid).prefetch_related("service")
    if not wechat_user:
        return fail(msg="用户不存在")
    userinfo = {
        "head_image": wechat_user.headimgurl,
        "nickname": wechat_user.nickname,
        "sex": wechat_user.sex,
        "access": req.state.scopes,
        "is_admin": req.state.is_admin,
        "service_name": wechat_user.service.service_name,
        "service_logo": wechat_user.service.service_logo
    }

    return success(userinfo, "userInfo")


async def delete_user(req: Request, user_id: int):
    """
    删除用户
    :param req:
    :param user_id:
    :return:
    """
    uid = req.state.uid
    # 当前用户
    user = await User.get_or_none(id=user_id, service=req.state.sid)
    # 不能删除其他服务商用户
    if not user:
        return fail(msg="当前用户不存，或者非本服务商用户")
    # 不能删除自己 出局了就没法玩了
    if uid == user.pk:
        return fail(msg="自己不能删除自己")
    # 非超级管理员不能修改超级官员的名字 备注
    if not req.state.is_admin and user.type:
        return fail(msg="你没有删除超级管理员的权限")
    # 执行删除
    await user.delete()
    return success(msg="删除成功")
